package UI;

import Model.User;
import java.net.UnknownHostException;
import javax.swing.*;
import java.awt.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * 
 */
/**
 *
 * @author Administrator
 */
public class Login extends javax.swing.JFrame {
    // create object
//    Connection  conn ;
//    Statement st = null;
//    ResultSet rs = null;
    Socket cs;
    ObjectOutputStream out;
    ObjectInputStream in;
     int count =0;
    /** Creates new form Login */
    public Login() {
        try {
            //super(parent, modal);            
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            initComponents();
            setBackground();
               
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }   
    //set background For Frame
    private void setBackground() {
        try {
            // get a Image to make the background
            ImageIcon imageBack = new ImageIcon(getClass().getResource("/Images/MainBackground.jpg"));
            //Set new image by scale with old image    
            Image imageicon = imageBack.getImage();
            Image newimage = imageicon.getScaledInstance(imageicon.getWidth(null) * 6 / 6, imageicon.getHeight(null) * 6 / 6, Image.SCALE_SMOOTH);
            imageBack.setImage(newimage);
            //Set Size Frame from image size
          //    setSize(imageBack.getIconWidth(),imageBack.getIconHeight());
            //Set background Image
            JLabel background = new JLabel(imageBack);
            background.setBounds(0, 0, imageBack.getIconWidth(), imageBack.getIconHeight());
            getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
            backGround.setOpaque(false);
            setContentPane(backGround);
            this.setLocationRelativeTo(null);
        } catch (Exception e) {
        }


    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        backGround = new javax.swing.JPanel();
        pnLogin = new javax.swing.JPanel();
        lblUsername = new javax.swing.JLabel();
        lblpassword = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        pwdPassword = new javax.swing.JPasswordField();
        btnLogin = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtServerName = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login Management System");
        setBackground(new java.awt.Color(0, 148, 148));
        setResizable(false);

        backGround.setBackground(new java.awt.Color(0, 204, 153));
        backGround.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        pnLogin.setBackground(new java.awt.Color(8, 158, 215));
        pnLogin.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Login System", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 24))); // NOI18N

        lblUsername.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblUsername.setText("Username");

        lblpassword.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblpassword.setText("Password");

        btnLogin.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Login.png"))); // NOI18N
        btnLogin.setText("Login");
        btnLogin.setMaximumSize(new java.awt.Dimension(100, 40));
        btnLogin.setPreferredSize(new java.awt.Dimension(100, 100));
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        btnExit.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Exitlogin.png"))); // NOI18N
        btnExit.setText("Exit");
        btnExit.setMaximumSize(new java.awt.Dimension(100, 40));
        btnExit.setMinimumSize(new java.awt.Dimension(100, 60));
        btnExit.setPreferredSize(new java.awt.Dimension(100, 100));
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Server Addess");

        txtServerName.setText("localhost");

        javax.swing.GroupLayout pnLoginLayout = new javax.swing.GroupLayout(pnLogin);
        pnLogin.setLayout(pnLoginLayout);
        pnLoginLayout.setHorizontalGroup(
            pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnLoginLayout.createSequentialGroup()
                .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnLoginLayout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblUsername)
                            .addComponent(lblpassword)
                            .addComponent(jLabel1))
                        .addGap(41, 41, 41)
                        .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtServerName)
                            .addComponent(pwdPassword)
                            .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)))
                    .addGroup(pnLoginLayout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(46, 46, 46)
                        .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(61, Short.MAX_VALUE))
        );
        pnLoginLayout.setVerticalGroup(
            pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnLoginLayout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblUsername)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pwdPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblpassword))
                .addGap(27, 27, 27)
                .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtServerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(pnLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout backGroundLayout = new javax.swing.GroupLayout(backGround);
        backGround.setLayout(backGroundLayout);
        backGroundLayout.setHorizontalGroup(
            backGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backGroundLayout.createSequentialGroup()
                .addGap(251, 251, 251)
                .addComponent(pnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(147, Short.MAX_VALUE))
        );
        backGroundLayout.setVerticalGroup(
            backGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, backGroundLayout.createSequentialGroup()
                .addContainerGap(189, Short.MAX_VALUE)
                .addComponent(pnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(114, 114, 114))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(backGround, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(backGround, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        try {
            cs.close();
           System.exit(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
    }//GEN-LAST:event_btnExitActionPerformed

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
         try {                                         
            // TODO add your handling code here:
            // action login management system
              
                String username = txtUsername.getText().toString().trim();
                String password = new String(pwdPassword.getPassword());
                String serverName = txtServerName.getText().toString().trim();
                if (username.equals("")) {
                    JOptionPane.showMessageDialog(null, "Username can not be blank !");
                    return;
                }
                if (password.equals("")) {
                    JOptionPane.showMessageDialog(null, "Password can not be blank !");
                    return;
                }  
                if (serverName.equals("")) {
                    JOptionPane.showMessageDialog(null, "Server Name can not be blank !");
                    return;
                }  
             
              cs = new Socket(serverName, 1234);//mo socket, goi yc kn den server
             //mo luong out,in de goi nhan du lieu voi server
              out = new ObjectOutputStream(new DataOutputStream(cs.getOutputStream()));
              in = new ObjectInputStream(new DataInputStream(cs.getInputStream()));
             User user=new User(username,password);
 
              out.writeObject("login");//goi request "login"     
                out.writeObject(user);//goi doi tuong user cho sever        
                 boolean   alert=(boolean)in.readObject();//nhan thong bao tu server    
                if(alert){
                    JOptionPane.showMessageDialog(null, "Welcom "+"~~"+username+"~~"+ "To Library Management System - DVT Ltd., !");
                    this.setVisible(false);
                    this.dispose(); 
                    cs.close();
                    out.close();
                    in.close();
                    MainFrame.Username = user.getUsername();
                    new MainFrame(user.getUsername(),serverName).setVisible(true);
                 }
                 else
                 {
                count++;
                JOptionPane.showMessageDialog(this,"Username or Password is invalid, please try again !!!\nYou have " + (3 - count) + " times to try.");
                 }
                if (count == 3) {
                System.exit(0);
                }    
           
            } catch (ClassNotFoundException| IOException ex) {  
                   JOptionPane.showMessageDialog(null,"Error on Server : "+ ex.getMessage()); 
                
            }
           
           
                
      
       
       
            
    }//GEN-LAST:event_btnLoginActionPerformed

    /**
     * @param args the command line arguments
     */
 public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Login dialog = new Login();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                     
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel backGround;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnLogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JLabel lblpassword;
    private javax.swing.JPanel pnLogin;
    private javax.swing.JPasswordField pwdPassword;
    private javax.swing.JTextField txtServerName;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
}
